package org.example.demo1.servlets.ManagePage;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.demo1.DAO.PermissionDao;
import org.example.demo1.DAO.RolePermissionDao;
import org.example.demo1.Entity.Permission;
import org.example.demo1.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.RoleDao;
import org.example.demo1.Entity.Role;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/API/role/add")
public class AddRoleServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        // 使用MyBatis获取SqlSession
        try (SqlSession sqlSession = MybatisUtils.getSqlSession()) {
            PermissionDao permissionDao = sqlSession.getMapper(PermissionDao.class);
            
            // 获取所有权限
            List<Permission> permissions = permissionDao.getAllPermissions();
            
            // 构建成功响应
            Map<String, Object> successResponse = new HashMap<>();
            successResponse.put("code", 200);
            successResponse.put("message", "获取权限列表成功");
            successResponse.put("data", permissions);
            
            // 返回JSON响应
            Gson gson = new Gson();
            out.write(gson.toJson(successResponse));
            
        } catch (Exception e) {
            // 记录异常
            e.printStackTrace();
            
            // 构建错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            
            // 返回JSON响应
            Gson gson = new Gson();
            out.write(gson.toJson(errorResponse));
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        // 读取请求体中的JSON数据
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String requestBody = sb.toString();
        
        // 解析JSON数据
        Gson gson = new Gson();
        Map<String, Object> requestData = gson.fromJson(requestBody, new TypeToken<Map<String, Object>>(){}.getType());
        
        // 提取角色信息
        String roleName = (String) requestData.get("role_name");
        String description = (String) requestData.get("description");
        List<Double> permissionIdsDouble = (List<Double>) requestData.get("permission_ids");
        List<Integer> permissionIds = new ArrayList<>();
        if (permissionIdsDouble != null) {
            for (Double id : permissionIdsDouble) {
                permissionIds.add(id.intValue());
            }
        }
        
        // 验证必填字段
        if (roleName == null || roleName.trim().isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "角色名称不能为空");
            out.write(gson.toJson(errorResponse));
            return;
        }
        
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
            RolePermissionDao rolePermissionDao = sqlSession.getMapper(RolePermissionDao.class);
            
            // 创建新角色对象
            Role newRole = new Role();
            newRole.setRole_name(roleName);
            newRole.setDescription(description);
            
            // 插入新角色
            int result = roleDao.insertRole(newRole);
            
            if (result > 0) {
                // 如果有权限需要分配，则进行分配
                if (!permissionIds.isEmpty()) {
                    for (Integer permissionId : permissionIds) {
                        rolePermissionDao.assignPermissionToRole(newRole.getRole_id(), permissionId);
                    }
                }
                
                // 提交事务
                sqlSession.commit();
                
                // 构建成功响应
                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("code", 200);
                successResponse.put("message", "角色添加成功");
                
                // 返回新角色的ID
                Map<String, Object> data = new HashMap<>();
                data.put("role_id", newRole.getRole_id());
                successResponse.put("data", data);
                
                out.write(gson.toJson(successResponse));
            } else {
                // 回滚事务
                if (sqlSession != null) {
                    sqlSession.rollback();
                }
                // 构建失败响应
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 500);
                errorResponse.put("message", "角色添加失败");
                out.write(gson.toJson(errorResponse));
            }
        } catch (Exception e) {
            // 回滚事务
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            e.printStackTrace();
            
            // 构建错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            out.write(gson.toJson(errorResponse));
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}
